package com.yfeng.exception;

import java.io.PrintStream;
import java.io.PrintWriter;

/**
 * Created by IntelliJ IDEA.
 * User: yfeng
 * Date: 2010-8-13
 * Time: 20:26:04
 */
/**
 * 系统异常基类
 * @version1.0
 * */
public class HomeException extends Exception{

	private static final long serialVersionUID = 8419589212554843672L;

	  /**
	   * 原因
	   */
	  private Throwable cause;

	  /**
	   * 默认构造函数
	   */
	  public HomeException() {
	    this(null, null);
	  }

	  /**
	   * @param cause 原因
	   * 带有嵌套异常的构造函数
	   */
	  public HomeException(Throwable cause) {
	    this(null, cause);
	  }

	  /**
	   * @param message 异常信息
	   *带有异常信息的构造函数
	   */
	  public HomeException(String message) {
	    this(message, null);
	  }

	  public HomeException(String inMsg, Throwable inCause) {
		     super( ""+inMsg);
		    this.cause = inCause ;
	  }

	  /**
	   * Get Cause
	   * 获取嵌套的异常
	   * @return cause throwable
	   */
	  public Throwable getCause() {
	    return cause;
	  }

	  /**
	   * Get Initial Cause
	   * 获取异常链中最初的异常.
	   */
	  public Throwable getInitialCause() {
	    if (cause == null) {
	      //自己是错误的原因
	      return this;
	    }
	    else {
	      if (cause instanceof HomeException) {
	        //递归查找错误的原因
	        return ( (HomeException) cause).getInitialCause();
	      }
	      else {
	        //保存的异常是错误的原因
	        return cause;
	      }
	    }
	  }

	  /**
	     * Prints the stack backtrace.
	     * 打印堆栈信息到System.err
	     */
	    public void printStackTrace() {
	        printStackTrace(System.err);
	    }

	    /**
	     * Prints the stack backtrace to the specified print stream.
	     * 打印堆栈信息到PrintStream
	     * @param inPS PrintStream
	     */
	    public void printStackTrace(PrintStream inPS) {
	        if (inPS == null) {
	            throw new NullPointerException("PrintStream can't be NULL");
	        }
	        synchronized (inPS) {
	            super.printStackTrace(inPS);

	            if (cause != null) {
	                inPS.println("caused by:");
	                cause.printStackTrace(inPS);
	            }
	        }
	    }

	    /**
	     * Prints the stack backtrace to the specified print writer.
	     * 打印堆栈信息到PrintWriter
	     * @param inPW PrintWriter
	     */
	    public void printStackTrace(PrintWriter inPW) {
	        if (inPW == null) {
	            throw new NullPointerException("PrintWriter can't be NULL");
	        }
	        synchronized (inPW) {
	            super.printStackTrace(inPW);

	            if (cause != null) {
	                inPW.println("caused by:");
	                cause.printStackTrace(inPW);
	            }
	        }
	    }
}
